package com.xunshangwang.pinhaohuo.ui.fragments;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.xunshangwang.pinhaohuo.R;
import com.xunshangwang.pinhaohuo.adapters.PinAdapter;
import com.xunshangwang.pinhaohuo.decorations.DividerItemDecoration;
import com.xunshangwang.pinhaohuo.decorations.OffsetItemDecoration;
import com.xunshangwang.pinhaohuo.entity.Goods;
import com.xunshangwang.pinhaohuo.entity.Pin;
import com.xunshangwang.pinhaohuo.http.HttpTool;
import com.xunshangwang.pinhaohuo.http.JsonHttpHandler;
import com.xunshangwang.pinhaohuo.ui.activities.GroupListActivity;
import com.xunshangwang.pinhaohuo.widgets.LMSizeRecyclerView;
import com.xunshangwang.pinhaohuo.widgets.RefreshLayout;

import org.json.JSONObject;

import java.security.Policy;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import tool.library.adapter.BaseRecyclerAdapter;
import tool.library.widget.LoadRecyclerView;

/**
 * Created by xzp on 16/3/8.
 */
public class PinGroupFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener,LoadRecyclerView.OnLoadListener,
        BaseRecyclerAdapter.OnItemClickListener{
    private RefreshLayout mRefresh;
    private LMSizeRecyclerView mRecycler;
    private PinAdapter mAdapter;
    private String mAttrId;
    public final static PinGroupFragment newInstance(String attrId){
        PinGroupFragment fragment=new PinGroupFragment();
        Bundle bundle=new Bundle();
        bundle.putString("attrId", attrId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(getArguments()!=null){
            mAttrId=getArguments().getString("attrId");
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_pin_group,container,false);
        mRecycler= (LMSizeRecyclerView) view.findViewById(R.id.pin_list);
        mRecycler.setLayoutManager(new LinearLayoutManager(inflater.getContext()));
        mRecycler.addItemDecoration(new DividerItemDecoration(inflater.getContext()) {
            @Override
            protected boolean canDraw(int position) {
                return position < mAdapter.getItemCount() - 1;
            }
        });
        mRecycler.addItemDecoration(new OffsetItemDecoration(inflater.getContext(),R.dimen.group_list_item_offset){
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                if(parent.getChildAdapterPosition(view)<mAdapter.getItemCount()-2)
                super.getItemOffsets(outRect, view, parent, state);
            }
        });
        mRefresh= (RefreshLayout) view.findViewById(R.id.refresh_layout);
        mRecycler.setOnLoadListener(this);
        mRefresh.setOnRefreshListener(this);
        mAdapter=new PinAdapter(inflater.getContext());
        mAdapter.setOnItemClickListener(this);
        mRecycler.setAdapter(mAdapter);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefresh.setRefreshing(true);
                onRefresh();
            }
        }, 150);
    }

    @Override
    public void onItemClick(BaseRecyclerAdapter adapter, View item, int position) {
        Goods goods=mAdapter.getList().get(position).getGoods_info();
        if(goods!=null) {
            Intent intent = new Intent(getContext(), GroupListActivity.class);
            intent.putExtra("goodsId", mAdapter.getList().get(position).getGoods_info().getGoods_id());
            startActivity(intent);
        }
    }

    @Override
    public void onRefresh() {
        requestRefresh();
    }

    @Override
    public void onLoad(LoadRecyclerView recyclerView) {
        requestLoad();
    }

    private void requestRefresh(){
        StringBuilder builder=new StringBuilder("?g=Api&m=Goods&a=fastJoin");
        builder.append("&offset=0");
        builder.append("&size=" + LMSizeRecyclerView.SIZE);
        builder.append("&attr_id=" + mAttrId);
        JsonHttpHandler<List<Pin>> httpHandler=new JsonHttpHandler<List<Pin>>() {
            @Override
            public List<Pin> parseData(JSONObject object) throws Throwable {
                return JSON.parseArray(object.getString("goods"),Pin.class);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mRefresh.setRefreshing(false);
            }
            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<Pin> response) {
                mAdapter.setList(response);
                mRecycler.loadFinish(response);
            }
        };
        httpHandler.setTag(getView());
        HttpTool.get(getContext(),builder.toString(),httpHandler);
    }
    private void requestLoad(){
        StringBuilder builder=new StringBuilder("?g=Api&m=Goods&a=fastJoin");
        builder.append("&offset="+mAdapter.getListSize());
        builder.append("&size=" + LMSizeRecyclerView.SIZE);
        builder.append("&attr_id=" + mAttrId);
        JsonHttpHandler<List<Pin>> httpHandler=new JsonHttpHandler<List<Pin>>() {
            @Override
            public List<Pin> parseData(JSONObject object) throws Throwable {
                return JSON.parseArray(object.getString("goods"),Pin.class);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, List<Pin> errorResponse) {
                super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
                mRecycler.loadFinish();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<Pin> response) {
                mAdapter.addAll(response);
                mRecycler.loadFinish(response);
            }
        };
        httpHandler.setTag(getView());
        HttpTool.get(getContext(),builder.toString(),httpHandler);
    }
}
